package com.example.demo.service.impl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.annotation.Resource;
import com.example.demo.Utils.TimeUtils;
import com.example.demo.bean.*;
import com.example.demo.mapper.DrinkMapper;
import com.example.demo.mapper.OrdersMapper;
import com.example.demo.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.ArrayList;
import java.util.Set;

import com.example.demo.requestentity.OrdersInsertRecords;
import com.example.demo.requestentity.OrdersRemoveRecords;
import com.example.demo.requestentity.OrdersUpdateRecords;
import com.example.demo.requestentity.OrdersRequestVO;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

@Service
public class OrdersServiceImpl implements OrderService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private DrinkMapper drinkMapper;

    @Override
    public ResultPageVO<OrdersVo> query(String name, Integer pageSize, Integer currentPage) {
        PageHelper.startPage(currentPage, pageSize);
        List<OrdersVo> ordersVoList = ordersMapper.query("%" + name + "%");
        for (int i = 1; i <= ordersVoList.size(); i++) {
            ordersVoList.get(i - 1).setId(String.valueOf(i));
        }
        return new ResultPageVO<>(new PageInfo<>(ordersVoList));
    }

    /**
     * 参数校验
     *
     * @param
     * @return
     * @author kongjiawei
     * @date 2021/9/7 11:24
     */
    private String verifyInsertParameter(List<OrdersInsertRecords> insertRecords, Set<String> userNames, Set<String> drinkNames) {
        for (OrdersInsertRecords record : insertRecords) {
            if (userNames.contains(record.getUName()) || !drinkNames.contains(record.getDrinkName())) {
                return "  插入参数校验失败！已经存在员工：" + record.getUName() + "   或没有此饮料：" + record.getDrinkName();
            }
        }
        return "校验成功";
    }

    private String verifyUpdateParameter(List<OrdersUpdateRecords> updateRecords, Set<String> userNames, Set<String> drinkNames) {
        for (OrdersUpdateRecords record : updateRecords) {
            if (!userNames.contains(record.getUName()) || !drinkNames.contains(record.getDrinkName())) {
                return "  更新参数校验失败！不存在该员工：" + record.getUName() + "   或没有此饮料：" + record.getDrinkName();
            }
        }
        return "校验成功";
    }


    /**
     * @param ordersRequestVO
     * @return
     * @author kongjiawei
     * @date 2021/8/29 23:22
     */
    @Override
    public ResultVO operation(OrdersRequestVO ordersRequestVO) {
        String date = TimeUtils.getNowTime();
        //插入操作
        List<OrdersInsertRecords> insertRecords = ordersRequestVO.getInsertRecords();
        List<String> insertDrinkNames = new ArrayList<>();
        int insertNums = 0;
        boolean flag = false;
        Set<String> userNames = ordersMapper.queryUnames();
        Set<String> drinkNames = drinkMapper.queryName();
        String message = "";
        if (insertRecords != null && insertRecords.size() > 0) {
            String verifyResult=verifyInsertParameter(insertRecords,userNames ,drinkNames );
            if(verifyResult.equals("校验成功")) {
                flag = true;
                for (OrdersInsertRecords record : insertRecords) {
                    insertDrinkNames.add(record.getDrinkName());
                }
                List<String> Ids = ordersMapper.queryByDrinkNames(insertDrinkNames);
                for (int i = 0; i < Ids.size(); i++) {
                    insertRecords.get(i).setDId(Ids.get(i));
                }
                insertNums = ordersMapper.insertBatch(insertRecords, date);
            }
            else{
                message+=verifyResult;
            }
        }

        //更新操作
        List<OrdersUpdateRecords> updateRecords = ordersRequestVO.getUpdateRecords();
        int updateNums = 0;
        if (updateRecords != null && updateRecords.size() > 0 ) {
            String verifyUResult = verifyUpdateParameter(updateRecords, userNames,drinkNames );
            if(verifyUResult.equals("校验成功")) {
                flag = true;
                List<String> updateDrinkNames = new ArrayList<>();
                for (OrdersUpdateRecords record : updateRecords) {
                    updateDrinkNames.add(record.getDrinkName());
                }
                List<String> upIds = ordersMapper.queryByDrinkNames(updateDrinkNames);
                for (int i = 0; i < upIds.size(); i++) {
                    updateRecords.get(i).setDId(upIds.get(i));
                }
                updateNums = ordersMapper.updateBatch(updateRecords, date);
            }
            else{
                message+=verifyUResult;
            }
        }

        //删除操作
        int removeNums = 0;
        List<OrdersRemoveRecords> removeRecords = ordersRequestVO.getRemoveRecords();
        List<String> uNames = new ArrayList<>();
        if (removeRecords != null && removeRecords.size() > 0 ) {
            for (OrdersRemoveRecords record : removeRecords) {
                uNames.add(record.getUName());
            }
            removeNums = ordersMapper.removeBatch(uNames);
        }
        if (flag&& removeNums >= 0) {
            return ResultVO.success(insertNums, removeNums, updateNums);
        }
        return ResultVO.error(message);

    }


    public int queryPeopleCount() {
       return ordersMapper.queryPeopleCount();
    }

    public void export() {
        List< ResultExportVO > resultExportVOS = ordersMapper.export();

        String uploadFile = "E:\\test\\output\\output.xlsx";
        OutputStream fos = null;
        try {
            fos = new FileOutputStream(uploadFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet();

        XSSFRow row = null;
        XSSFCell cell = null;

        row = sheet.createRow(0);
        String[] names = {"饮料名称","总数","地点"};
        for (int index = 0; index <= 2; index++) {
            cell = row.createCell(index);
            cell.setCellValue(names[index]);
        }
        int startRow = 1;
        for (ResultExportVO rev:resultExportVOS) {
            row = sheet.createRow(startRow);
            cell = row.createCell(0);
            cell.setCellValue(rev.getDrinkname());
            cell = row.createCell(1);
            cell.setCellValue(rev.getCount());
            cell = row.createCell(2);
            cell.setCellValue(rev.getWork_place());
            startRow++;
        }
        try {
            workBook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
